package com.hundsun.yr.universal.p2p.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.widget.ClickableTextView;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSEditText;
import com.hundsun.yr.universal.p2p.bean.AuthListBean;
import com.hundsun.yr.universal.p2p.bean.LoanProductBeen;
import com.hundsun.yr.universal.p2p.bean.LoanRateBean;
import com.hundsun.yr.universal.p2p.bean.PickerBean;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.bean.enums.OssidEnum;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.datahandler.LoanHandler;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.utils.RefundDayUtils;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;
import com.hundsun.yr.universal.p2p.view.pop.wheel.OptionsPickerView;
import com.hundsun.yr.universal.p2p.widget.AddSubView;
import com.hundsun.yr.universal.p2p.widget.ItemView;
import com.qiyukf.nim.uikit.common.ui.listview.AutoRefreshListView;

import java.math.BigDecimal;
import java.util.ArrayList;

/**
 * 借款-申请借款页面
 *
 * @author tonglj
 */
@SuppressWarnings("rawtypes")
public class IWantLoanActivity extends BaseActivity implements OnClickListener, View.OnLayoutChangeListener, InitializeView,
        AddSubView.OnNumChangeListener,
        HSDialog.HSDialogOnItemClickListener{

    /**
     * 钱
     */
    private HSEditText et_apply_amount;

    /**
     * 申请额度的单位
     */
    private String apply_amount_unit = "10000";
    /**
     * 申请额度提示信息
     */
//    private TextView tv_hint;
/*    *//**
     * 问号图标
     *//*
    private View iv_question;*/
    /**
     * 借款期限选择项
     */
    private TextView tv_life_of_loan;
    /**
     * 借款期限
     */
    private EditText et_life_of_loan;
    /**
     * 募集期限
     */
    private ItemView itemRaisingPeriod;
    /**
     * 还款方式
     */
    private ItemView itemRepaymentMethod;
    /**
     * 借款用途
     */
    private ItemView itemLoanUse;

    /**
     * 服务费率
     */
    private ItemView itemv_service_fee;
    /**
     * 风险准备金率
     */
//    private ItemView itemv_risk_fee;
    /**
     * 提交按钮
     */
    private HSButton btn_Submit;


    private OptionsPickerView mPickerView;
    /**
     * 存放PickerView选项
     */
    private ArrayList<PickerBean> optionsItems = new ArrayList<PickerBean>();

    private ClickableTextView tv_loanOss;
    /**
     * 还款利率
     */
    private AddSubView asv_refundRate;

    /**
     * 协议勾选框
     */
    private CheckBox checkbox;
    /**
     * 综合成本
     */
//    private TextView tv_compositeCost;

    /**
     * 预还款日
     */
    private ItemView item_returnday;

    public final static int LoanTermDay = 0;
    public final static int LoanTermMounth = 1;
    /**
     * 服务费率列表
     */
    private ArrayList<LoanRateBean> rates;
    /**
     * 最小借款期限
     */
    private int minTerm = 0;
    /**
     * 最大借款期限
     */
    private int maxTerm = 0;
    /**
     * 授信有效时间
     */
//	private long validTime;
    /**
     * 借款对象，LoanFragemnt带来的数据
     */
    private LoanProductBeen bean;

    /**需要上传的数据**/
    /**
     * 借款产品id
     **/
    private String loanid;
    /**
     * 借款金额
     **/
    private String amount;
    /**
     * 借款期限
     **/
    private String term;
    /**
     * 借款利率
     **/
    private String rate = "";
    /**
     * 用途
     **/
    private String purpose;
    /**
     * 减息卷id
     **/
    private String ratecutid;
    /**
     * 还款方式
     **/
    private String pay_method;

    /**
     * 剩余可用授信
     */
    private TextView tv_can_use_money;

    /**
     *
     */
//    private LinearLayout ll_iwant_borrow;

    /**
     * mPresenter
     */
    private RequestPresenter mPresenter;

    /**
     * 软件盘弹起后所占高度阀值
     **/
    private int keyHeight = 0;

    /**
     * 综合成本
     */
//    private LinearLayout ll_composite_cost;

    /**
     * 最小借款期限
     */
    private String term_min;
    /**
     * 最大借款期限
     */
    private String term_max;

    private String service_fee = "";
    private String risk_fee = "";
    private String[] purpose_list;
    private String zwgt_data;

    private TextView tv_risk_tips = null;

    private AuthListBean mAuthListBean = null;

    private TextView tv_checkbox = null;

    /**
     * 缴费授权金额
     * @param v
     */
    private HSDialog payFeeDialog;

    /**
     * 还款授权金额
     * @param v
     */
    private HSDialog repFeeDialog;
    @SuppressWarnings("unchecked")
    @Override
    public void onClick(View v) {

        if (isFastDoubleClick()){
            return;
        }

        switch (v.getId()) {
            case R.id.btn_wangtloan_submit://申请借款
                btn_Submit.setEnabled(false);
                // TODO: 2017/5/23 借款期限问题
                //借款期限
                if (!TextUtils.isEmpty(RefundDayUtils.showMsg(RefundDayUtils.tagType))) {
                    et_life_of_loan.setText("");
                    showToast(RefundDayUtils.showMsg(RefundDayUtils.tagType));
                    return;
                }

                if (!et_life_of_loan.getText().toString().isEmpty()) {
                    term = et_life_of_loan.getText().toString();
                } else {
                    showToast(getString(R.string.borrow_term));
                    return;
                }

                if (term_max == null || term_min == null){
                    showToast("未获取借款期限");
                    return;
                }

                // TODO: 2017/5/23 不同类型产品需要一样的最大最小期限

                if (TextUtils.equals(pay_method, "1")) {
                    if (MathUtils.compare(et_life_of_loan.getText().toString(), term_max) > 0) {
                        //借款期限不能大于最大可借款期限，最大可借款期限为360天
                        showToast(getString(R.string.borrow_term_max, term_max));
                        return;
                    }

                    if (MathUtils.compare(et_life_of_loan.getText().toString(), term_min) < 0) {
                        //借款期限不能小于最小可借款期限，最小可借款期限为10天
                        showToast(getString(R.string.borrow_term_min, term_min));
                        return;
                    }

                } else {
                    if (MathUtils.compare(et_life_of_loan.getText().toString(), term_max) > 0) {
                        showToast(getString(R.string.borrow_term_month_max, term_max));
                        return;
                    }

                    if (MathUtils.compare(et_life_of_loan.getText().toString(), term_min) < 0) {
                        showToast(getString(R.string.borrow_term_month_min, term_min));
                        return;
                    }
                }

                //借款用途校验
                if (purpose.isEmpty()) {
                    showToast(getString(R.string.loan_use_no_empty));
                    return;
                }


                //借款金额
                if (!et_apply_amount.getText().toString().isEmpty()) {
                    amount = et_apply_amount.getText().toString();
                } else {
                    showToast(getString(R.string.borrow_amount));
                    return;
                }

                /*if (MathUtils.compare(bean.debt_min, bean.remain_credit) < 0) {
                    if (MathUtils.compare(amount, bean.debt_min) < 0) {
                        //借款金额不能小于最小借款金额
                        showToast(getString(R.string.borrow_min));
                        return;
                    }
                }*/

                if (MathUtils.compare(amount, bean.debt_max) > 0) {
                    //借款金额不能大于最大借款金额
                    showToast(getString(R.string.borrow_max));
                    return;
                }

//                // TODO: 2017/9/29 检查最小可借款金额
//                if (MathUtils.compare(amount, bean.remain_credit) > 0) {
//                    showToast(getString(R.string.your_credit_not_enough));
//                    return;
//                } else if (MathUtils.compare(amount, bean.remain_credit) < 0) {
//                    //如果客户的借款金额小于授信金额，则需要检查借款递增金额
//                    if (new Double(MathUtils.subtract(amount,bean.debt_min)) % new Double(bean.debt_step) != 0 && MathUtils.compare(bean.debt_min, amount) != 0) {
//                        showToast(getString(R.string.borrow_step_amount, bean.debt_step));
//                        return;
//                    }
//                } else {
//                    //借款金额等于授信额度的时候，不需要检查递增金额
//                    // TODO: 2017/9/29 这边还要和最小起借金额进行一个比较
//                    if (MathUtils.compare(bean.remain_credit,bean.debt_min) > 0){
//                        if (new Double(MathUtils.subtract(amount,bean.debt_min)) % new Double(bean.debt_step) != 0 && MathUtils.compare(bean.debt_min, amount) != 0) {
//                            showToast(getString(R.string.borrow_step_amount, bean.debt_step));
//                            return;
//                        }
//                    }
//                }
                // TODO: 2017/11/3  检查金额的新规则
                //以下是正向思维方式的思想
                if (MathUtils.compare(bean.debt_min, bean.remain_credit) >= 0){
                    //最小可借金额 >= 用户可用授信额度 不需要判断任何条件直接可借 因为用户输入的钱不会动了钱是默认值（用户可用授信额度）

                } else {

                    //最小可借金额 < 用户可用授信额度
/*                    if (MathUtils.compare(bean.remain_credit, amount) >= 0){
                        //用户可用授信额度 >= 用户输入的借款金额
                        if (MathUtils.compare(amount,bean.debt_min) >= 0){
                            //用户输入金额>=用户最小可借金额
                            if (new Double(MathUtils.subtract(amount,bean.debt_min)) % new Double(bean.debt_step) != 0) {
                                showToast(getString(R.string.borrow_step_amount, bean.debt_step));
                                return;
                            }
                        } else {
                            //用户输入金额<用户最小可借金额
                            showToast(getString(R.string.borrow_min));
                            return;
                        }
                    } else {
                        //用户可用授信额度 < 用户输入的借款金额
                        showToast(getString(R.string.your_credit_not_enough));
                        return;
                    }*/

                    //同样目的的规则
                    if (MathUtils.compare(bean.remain_credit, amount) < 0){
                        //用户可用授信额度 < 用户输入的借款金额
                        showToast(getString(R.string.your_credit_not_enough));
                        return;
                    }

                    //用户可用授信额度 >= 用户输入的借款金额
                    if (MathUtils.compare(amount,bean.debt_min) < 0){
                        //用户输入借款金额<用户最小可借金额
                        showToast(getString(R.string.borrow_min));
                        return;
                    }

                    //用户可用授信额度 >= 用户输入的借款金额 && 用户输入的借款金额>=用户最小可借金额
                    if (new Double(MathUtils.subtract(amount,bean.debt_min)) % new Double(bean.debt_step) != 0) {
                        //不符合递增规则
                        showToast(getString(R.string.borrow_step_amount, bean.debt_step));
                        return;
                    }
                }

                //借款协议必须勾选
                //验证ck_agree是否勾选
                if (checkbox.isChecked() == false) {
                    showToast(getString(R.string.tips_agree_protocol, OssidEnum.LOAN_SERVICE_PROTOCOL.getOssLabel()));
                    return;
                }
                //缴费授权金额
//                payFeeDialog = new HSDialog(getString(R.string.tips), "应收费用标准超出缴费授权金额，请重新签订缴费授权。", "暂不签约",
//                        "重新签约", mContext, this).setCancelable(false);
//                payFeeDialog.show();
//
//                //还款授权金额
//                repFeeDialog = new HSDialog(getString(R.string.tips), "借款总成本超出还款授权金额，请重新签订还款授权。", "暂不签约",
//                        "重新签约", mContext, this).setCancelable(false);
//                repFeeDialog.show();
                rate = asv_refundRate.getNum() + "";
                // TODO: 2017/6/6 还有一个减息卷
                mDataHandler.interactive(mDataHandler, R.string.method_addBorrowApply, loanid, amount, term, rate, purpose, "", pay_method, bean.name, bean.trustee_flag,CommTool.keep1Digits(service_fee));

                break;
            case R.id.itemv_loan_use://借款用途
                optionsItems.clear();
                final ArrayList<String> optionsItems = new ArrayList<String>();
//                String[] loanUse = getResources().getStringArray(R.array.loan_use);

                optionsItems.addAll(CommTool.arr2ArrList(purpose_list));
                // 选项选择器
                mPickerView.setPicker(optionsItems);
                mPickerView.setCyclic(false);
                mPickerView.setTitle(getString(R.string.loan_use));
                // 加载数据
                mPickerView.show();
                mPickerView.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int option1, int option2, int option3) {
                        itemLoanUse.setValue(optionsItems.get(option1));
                        purpose = optionsItems.get(option1);
//						params.setLoanUse(optionsItems.get(option1));
//                        setSubmitAble();
                    }
                });
                break;

            case R.id.tv_loanoss://借款协议
                Bundle bundle = new Bundle();
                bundle.putString("protocol_name",bean.protocol_name);
                bundle.putString("protocol_url",bean.protocol_url);
                readyGo(WebViewPDFTest.class,bundle);
                break;

            case R.id.tv_checkbox:
                checkbox.setChecked(!checkbox.isChecked());
                break;
        }
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return true;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_wantloan;
    }

    @Override
    protected void initViewsAndEvents() {
        findView();

        //反射网络请求需要用到的类
        mPickerView = new OptionsPickerView(this);
        toolbar_title.setText(R.string.i_want_loan);
//        iv_question.setOnClickListener(this);
        btn_Submit.setOnClickListener(this);
        btn_Submit.setEnabled(false);
        itemLoanUse.setOnClickListener(this);
        tv_loanOss.setOnClickListener(this);

        //反射网络请求
        mDataHandler = new LoanHandler(mContext);

        //添加监听
        et_apply_amount.addTextChangedListener(textWatcher1);
        et_apply_amount.setHint(getString(R.string.debtmin_debtstep, CommTool.moneyOneThousandsFormat(bean.debt_min), CommTool.moneyOneThousandsFormat(bean.debt_step
        )));
        et_life_of_loan.addTextChangedListener(textWatcher2);

        //更具不同的产品进行不同的借款期限的提示
        if (TextUtils.equals(pay_method, "1")) {
            //循环遍历
            for (int i = 0; i < bean.rate_list.size(); i++){
                if (i == 0){
                    term_min = bean.rate_list.get(i).term_min;
                }

                if (i == bean.rate_list.size() - 1){
                    term_max = bean.rate_list.get(i).term_max;
                }
            }
            et_life_of_loan.setHint(term_min + "~" + term_max);
        } else if (TextUtils.equals(pay_method, "2") || TextUtils.equals(pay_method, "3") || TextUtils.equals(pay_method, "4")) {

            //循环遍历
            for (int i = 0; i < bean.rate_list.size(); i++){
                if (i == 0){
                    term_min = bean.rate_list.get(i).term_min;
                }

                if (i == bean.rate_list.size() - 1){
                    term_max = bean.rate_list.get(i).term_max;
                }
            }

            et_life_of_loan.setHint(term_min + "~" + term_max);
        }

        asv_refundRate.setMaxValue(0);
        asv_refundRate.setNum(0);
        asv_refundRate.setMinValue(0);

//        /***
//         * 根据服务器数据显示显示综合成本
//         */
//        if (TextUtils.equals(bean.show_cost_flag,"0")){
//            ll_composite_cost.setVisibility(View.GONE);
//        } else {
//            //显示综合成本
//            ll_composite_cost.setVisibility(View.VISIBLE);
//        }

        /***
         * 根据服务器数据，显示purpose_list
         */
        purpose_list = bean.purpose_list.split(",");

        //设置最大募集期限
        itemRaisingPeriod.setValue(mContext.getString(R.string._day, bean.raise_term));
        itemRaisingPeriod.setRealValue(bean.raise_term + "");

        //设置还款方式
        itemRepaymentMethod.setValue(bean.getPayMethod(mContext));

        //借款用途，默认借款用途消费
        itemLoanUse.setValue("");
        purpose = "";

        if (bean.purpose_list == null || bean.purpose_list.isEmpty()){//拿不到服务端借款用途的时候
            itemLoanUse.setVisibility(View.GONE);
            btn_Submit.setEnabled(false);
        } else {
            itemLoanUse.setValue(purpose_list[0]);
            purpose = purpose_list[0];
        }

        //剩余可用授信
        tv_can_use_money.setText(getString(R.string.can_use_money, CommTool.keep2Digits(bean.remain_credit)));

        if (MathUtils.compare(bean.debt_min, bean.remain_credit) >= 0) {
            //最小可借金额大于剩余可用授信的时候
            et_apply_amount.setText(bean.remain_credit);

            et_apply_amount.setEnabled(false);
            et_apply_amount.setRightIconVisible(false);
        }

        if (bean.risk_msg != null && !bean.risk_msg.isEmpty()){
            tv_risk_tips.setText(bean.risk_msg);
        }

        keyHeight = mScreenHeight / 3;

        btn_Submit.addOnLayoutChangeListener(this);
        mPresenter = new InitializePresenterImpl(mContext, this);

        asv_refundRate.setOnNumChangeListener(this);

        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    if (et_apply_amount.getText().toString() != null && !et_apply_amount.getText().toString().isEmpty() &&
                    et_life_of_loan.getText().toString() != null && !et_life_of_loan.getText().toString().isEmpty()){
                        btn_Submit.setEnabled(true);
                    }
                } else {
                    btn_Submit.setEnabled(false);
                }
            }
        });

        tv_checkbox.setOnClickListener(this);
    }

    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    private void findView() {
        item_returnday = findView(R.id.item_returnday);
        et_apply_amount = findView(R.id.et_apply_amount);
//        tv_hint = findView(R.id.hint_apply_amount);
//        iv_question = findView(R.id.iv_wantloan_question);
        tv_life_of_loan = findView(R.id.hint_life_of_loan);

        //不同的借款产品设置不同的借款期限单位
        pay_method = bean.pay_method;
        if (!TextUtils.equals(pay_method, "1")) {
            tv_life_of_loan.setText(getString(R.string.month));
        }

//        tv_life_of_loan.setVisibility(View.GONE);

        et_life_of_loan = findView(R.id.et_life_of_loan);
        btn_Submit = findView(R.id.btn_wangtloan_submit);

        itemRaisingPeriod = findView(R.id.itemv_raising_period);
        itemRepaymentMethod = findView(R.id.itemv_repayment_method);
        itemLoanUse = findView(R.id.itemv_loan_use);
        tv_loanOss = findView(R.id.tv_loanoss);
        asv_refundRate = findView(R.id.asv_refund_rate);
        checkbox = findView(R.id.checkbox);
//        tv_compositeCost = findView(R.id.composite_cost);
        tv_can_use_money = findView(R.id.tv_can_use_money);
//        ll_iwant_borrow = findView(R.id.ll_iwant_borrow);
//        ll_composite_cost = findView(R.id.ll_composite_cost);
        itemv_service_fee = findView(R.id.itemv_service_fee);
//        itemv_risk_fee = findView(R.id.itemv_risk_fee);
        tv_risk_tips = findView(R.id.tv_risk_tips);
        tv_checkbox = findView(R.id.tv_checkbox);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void getBundleExtras(Bundle extras) {
        bean = (LoanProductBeen) extras.getSerializable(Extras.DATA);
        mAuthListBean = (AuthListBean) extras.getSerializable(Extras.AUTHLIST);

        //借款id由上个页面携带
        loanid = bean.id;
    }


    @Override
    protected void onEveComming(EventCenter eventCenter) {
    }


    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void onNetworkConnected(NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    /**
     * 借款期限的监听
     */
    TextWatcher textWatcher2 = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {

            income();

            if (s.toString().isEmpty()) {
                item_returnday.setValue("");
            }

            //如果为空就return
            if (s.toString().isEmpty() || MathUtils.equals(s.toString(),"0") || itemLoanUse.getValue().isEmpty()) {
                btn_Submit.setEnabled(false);
                return;
            }

            if (et_apply_amount.getText().toString().isEmpty() || MathUtils.equals(et_apply_amount.getText().toString(),"0") || itemLoanUse.getValue().isEmpty()) {
                btn_Submit.setEnabled(false);
                return;
            }

            if (!checkbox.isChecked()){
                btn_Submit.setEnabled(false);
                return;
            }

            btn_Submit.setEnabled(true);

        }
    };

    /**
     * 借款金额监听
     */
    TextWatcher textWatcher1 = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {

            if (et_life_of_loan.getText().toString().isEmpty()) {
                item_returnday.setValue("");
            } else {
                income();
            }

            if (s.toString().isEmpty() || MathUtils.equals(s.toString(),"0") || itemLoanUse.getValue().isEmpty()) {
                btn_Submit.setEnabled(false);
                return;
            }

            if (et_life_of_loan.getText().toString().isEmpty() || MathUtils.equals(et_life_of_loan.getText().toString(),"0") || itemLoanUse.getValue().isEmpty()) {
                btn_Submit.setEnabled(false);
                return;
            }

            if (!checkbox.isChecked()){
                btn_Submit.setEnabled(false);
                return;
            }

            btn_Submit.setEnabled(true);
        }
    };

    /**
     * 根据借款期限改变借款利率
     *
     */
    private void income() {
        //以上两个监听只要为零的时候就将所有计算的东西清零
        if (et_life_of_loan.getText().toString().isEmpty() || et_apply_amount.getText().toString().isEmpty() || MathUtils.equals(et_life_of_loan.getText().toString(),"0") || MathUtils.equals(et_apply_amount.getText().toString(),"0")){
//            tv_compositeCost.setText(mContext.getString(R.string._rmb, "0"));
            asv_refundRate.setNum(0);
            asv_refundRate.setMaxValue(0);
            asv_refundRate.setMinValue(0);
            itemv_service_fee.setValue("未选择");
//            itemv_risk_fee.setValue("未选择");
            return;
        }

        int term = 0;
        /**有内容时候的计算公式**/
        if(CommTool.isDouble(et_life_of_loan.getText().toString())){
            term = Integer.valueOf(et_life_of_loan.getText().toString());
        }

        item_returnday.setValue(RefundDayUtils.returnDay(bean.pay_method, true, term));

        tv_life_of_loan.setTextColor(IWantLoanActivity.this.getResources().getColor(R.color.cl_item_right_hint_text));
        tv_life_of_loan.setVisibility(View.VISIBLE);

        //循环遍历
        for (int i = 0; i < bean.rate_list.size(); i++){
            if (MathUtils.compare(bean.rate_list.get(i).term_min,term + "") <= 0 && MathUtils.compare(bean.rate_list.get(i).term_max,term + "") >= 0){
                rate = bean.rate_list.get(i).debt_rate;
                service_fee = bean.rate_list.get(i).service_fee_show;
                risk_fee = bean.rate_list.get(i).risk_fee;
                break;
            }
        }

        if (service_fee == null || service_fee.isEmpty()){
            itemv_service_fee.setValue("0.0" + "%");
        } else {
            itemv_service_fee.setValue(CommTool.keep1Digits(service_fee) + "%");
        }

//        if (risk_fee == null || risk_fee.isEmpty()){
//            itemv_risk_fee.setValue("0.0" + "%");
//        } else {
//            itemv_risk_fee.setValue(CommTool.keep1Digits(risk_fee) + "%");
//        }

        if (rate.isEmpty() || TextUtils.isEmpty(rate)) {
            rate = "0";
        }

        asv_refundRate.setNum(Double.valueOf(rate));
        asv_refundRate.setMinValue(Double.valueOf(rate));
        asv_refundRate.setMaxValue(15);
//        rate = asv_refundRate.getNum() + "";


//        BigDecimal service_rate = null;
//        if (service_fee == null || service_fee.isEmpty()){
//            service_rate = new BigDecimal(0);
//        } else{
//            service_rate = new BigDecimal(service_fee);
//        }
//
//        BigDecimal risk_fee_rate = null;
//        if (service_fee == null || risk_fee.isEmpty()){
//            risk_fee_rate = new BigDecimal(0);
//        } else{
//            risk_fee_rate = new BigDecimal(risk_fee);
//        }

//        BigDecimal all_rate =  new BigDecimal(rate).add(service_rate).add(risk_fee_rate);

//        getzhcb(rate, all_rate);
    }

    private void getzhcb(String rate, BigDecimal all_rate) {
        if (MathUtils.equals(rate,"0") || MathUtils.equals(all_rate.toString(),"0")){
//            tv_compositeCost.setText(mContext.getString(R.string._yuan,0));
            return;
        }

        amount = et_apply_amount.getText().toString();
        //双重保障
        if (amount.isEmpty()) {
            return;
        }

        BigDecimal all_money;
        if (!et_apply_amount.getText().toString().isEmpty()) {
            all_money = new BigDecimal(this.amount);
        } else {
            all_money = new BigDecimal(0);
        }

        try{
            //根据不同的还款方式，生成不同的还款综合成本
            BigDecimal monthRate = new BigDecimal(Double.valueOf(all_rate.toString()) / 100).divide(new BigDecimal(12), 10,BigDecimal.ROUND_HALF_EVEN);

            BigDecimal add = null;
            switch (bean.pay_method) {
                case "1"://到期还本付息
                    add = (all_money.multiply(all_rate).multiply(new BigDecimal(et_life_of_loan.getText().toString()))).divide(new BigDecimal(360), 10,BigDecimal.ROUND_HALF_EVEN).divide(new BigDecimal(100), 10,BigDecimal.ROUND_HALF_EVEN);
                    break;
                case "2"://按月还息，到期还本
                    BigDecimal Xt2 = (all_money.multiply(monthRate)).multiply(new BigDecimal(et_life_of_loan.getText().toString()));
                    add = Xt2;
                    break;
                case "3"://等额本息
                    if (TextUtils.equals(rate, "0")) {
                        add = all_money;
                    } else {
                        //利率不为零，计算方式较为复杂  n×a×i×（1＋i）^n÷〔（1＋i）^n－1〕 n期数  a贷款金额  i月利率
                        BigDecimal multiply = new BigDecimal(et_life_of_loan.getText().toString()).multiply(all_money).multiply(monthRate).multiply((new BigDecimal(1).add(monthRate)).pow(Integer.valueOf(et_life_of_loan.getText().toString())));
                        BigDecimal subtract = (new BigDecimal(1).add(monthRate)).pow(Integer.valueOf(et_life_of_loan.getText().toString())).subtract(new BigDecimal(1));

                        BigDecimal a = subtract.setScale(2,BigDecimal.ROUND_HALF_DOWN);
                        BigDecimal b = new BigDecimal(0).setScale(2,BigDecimal.ROUND_HALF_DOWN);

                        if (!b.equals(a)){
                            add = multiply.divide(subtract, 5);
                        } else{
                            add = new BigDecimal(0);
                        }
                    }
                    break;
                case "4"://等额本金
                    BigDecimal multiply = (new BigDecimal(et_life_of_loan.getText().toString()).add(new BigDecimal(1))).multiply(all_money).multiply(monthRate);
                    add = multiply;
                    break;
            }

            //计算总还款金额
//        tv_compositeCost.setText(mContext.getString(R.string._yuan, add.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
//            tv_compositeCost.setText(CommTool.moneyOneThousandsFormat(add.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + ""));
        }catch (Exception e){
//            tv_compositeCost.setText("");
        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right,
                               int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if (oldBottom != 0 && bottom != 0 && oldBottom - bottom > keyHeight) {

        } else if (oldBottom != 0 && bottom != 0 && bottom - oldBottom > keyHeight) {

        }
    }

    @Override
    public <T> void initializeViews(String task_name, T data) {
    }

    @Override
    public <T> void initializeError(String task_name, T data) {

    }

    /**
     * AddSubView数字监听
     * @param view
     *            整个AddAndSubView
     * @param num
     */
    @Override
    public void onNumChange(View view, double num) {
        if (!et_apply_amount.getText().toString().isEmpty() && !et_life_of_loan.getText().toString().isEmpty()/* && !MathUtils.equals(et_apply_amount.getText().toString(),"0")*/){
            if (CommTool.isDouble(num + "") && CommTool.isDouble(service_fee) && CommTool.isDouble(risk_fee)){
                getzhcb(num + "",new BigDecimal(num).add(new BigDecimal(service_fee)).add(new BigDecimal(risk_fee)));
            }
        }
    }

    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if ( time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mPickerView.isShowing()){
                mPickerView.dismiss();
                return true;
            } else {
                return super.onKeyDown(keyCode,event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onItemClick(Object o, int position) {
        // 缴费授权
        if (o == payFeeDialog&&position!=-1) {
            readyGo(ManagementActivity.class);
        }
        //还款授权
        else if(o==repFeeDialog&&position!=-1){
            readyGo(ManagementActivity.class);
        }
    }
}
